package com.boomkeeper.mail.sender;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import com.boomkeeper.core.config.BaseConfig;
import com.boomkeeper.core.model.ChangeOrderData;
import com.boomkeeper.mail.template.MailTemplate;

/**
 * 发送邮件
 * @author zhangyu15
 */
@Component("myMailSender")
public class MailSender {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(MailSender.class);

	@Autowired
	private JavaMailSender javaMailSender;
	
	@Autowired
	private MailTemplate mailTemplate;
	
	@Autowired
	private BaseConfig baseConfig;
	
	/**
	 * 发送邮件
	 * @param changeOrderData 变更单数据模型
	 * @param ftlName 邮件模板名，如果为null，则使用默认邮件模板，如果使用自定义模板(模板需要与数据模型changeOrderData对应)，将模板放在resources/templates/下即可，
	 * 入参ftlName传入自定义模板的文件名
	 */
	public void sendHtmlMail(ChangeOrderData changeOrderData, String ftlName) {
		if (StringUtils.isBlank(ftlName)) {
			ftlName = baseConfig.getEmail().getTemplateName();
		}
		String htmlStr = mailTemplate.parseTemplateToHtml(changeOrderData, ftlName);
		this.sendHtmlMail(htmlStr);
	}
	
	/**
	 * 发送HTML邮件，一般用来测试，通常是一个静态的HTML模板
	 */
	public void sendDefaultHtmlMail() {
		String htmlStr = mailTemplate.parseTemplateToHtml(baseConfig.getEmail().getTemplateName());
		this.sendHtmlMail(htmlStr);
	}
	
	/**
	 * 发送HTML邮件主方法
	 * @param htmlString
	 */
	public void sendHtmlMail(String htmlString) {
		if (this.baseConfig.getEmail().isSendEmail()) {
			try {
				MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
				MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
				mimeMessageHelper.setFrom(baseConfig.getEmail().getFrom());
				mimeMessageHelper.setTo(baseConfig.getEmail().getToArray());
				mimeMessageHelper.setCc(baseConfig.getEmail().getCcArray());
				mimeMessageHelper.setSubject(baseConfig.getEmail().getSubject());
				mimeMessageHelper.setText(htmlString, true);
				
				this.javaMailSender.send(mimeMessage);
			} catch (MessagingException e) {
				LOGGER.error("发送邮件异常", e);
			}
		} else {
			LOGGER.error("邮件开关未开启");
		}
	}
	
	public void sendSimpleMail() {
		if (this.baseConfig.getEmail().isSendEmail()) {
			SimpleMailMessage message = new SimpleMailMessage();
			message.setFrom("516628260@qq.com");
			message.setTo("zhangyu15@asiainfo.com");
			message.setSubject("主题：简单邮件");
			message.setText("测试邮件内容");
			javaMailSender.send(message);
		}
	}
}
